using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using server.status_db;
using EFCore.BulkExtensions;
using System.Linq.Dynamic.Core;
using System.Dynamic;
[Authorize]
public class Xsjbxx_newsController : ODataController
{
    private status_oneContext _db;
    readonly ILogger<Xsjbxx_newsController> _log;
    public Xsjbxx_newsController(status_oneContext context, ILogger<Xsjbxx_newsController> log)
    {
        _db = context;
        _log = log;
    }
    private bool MCExists(Guid key)
    {
        return _db.PG_B_XSJBXX_New.Any(p => p.ID == key);
    }
    [HttpPut]
    public async Task<IActionResult> Put([FromODataUri] Guid key, [FromBody]PG_B_XSJBXX_New update)
    {

        try
        {
            if (!ModelState.IsValid)
            {

                var message = string.Join(" | ", ModelState.Values
                               .SelectMany(v => v.Errors)
                               .Select(e => e.Exception.Message));
                _log.LogError(this.User.Identity.Name + "," + message);
                return StatusCode(500, message);
            }
            if (key != update.ID)
            {
                return StatusCode(500, "key not eq id");
            }
            _db.Entry(update).State = EntityState.Modified;
            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException e)
            {

                var message = "多用户不能同时修改同一条数据";
                _log.LogError(this.User.Identity.Name + "," + message);
                return StatusCode(500, message);

            }
            return Updated(update);
        }
        catch (Exception e)
        {
            _log.LogError(this.User.Identity.Name + "," + e.ToString());
            return StatusCode(500, e.Message.ToString());
        }
    }
    public async Task<IActionResult> Delete([FromODataUri] int key)
    {
        try
        {
            var mc = await _db.PG_B_XSJBXX_New.FindAsync(key);
            if (mc == null)
            {
                var message = "没有发现要删除的对象Id";
                 _log.LogError(this.User.Identity.Name + "," + message);
                return StatusCode(500,message);
            }
            _db.PG_B_XSJBXX_New.Remove(mc);
            await _db.SaveChangesAsync();
            return NoContent();
        }
        catch (Exception e)
        {
            _log.LogError(this.User.Identity.Name + "," + e.ToString());
            return StatusCode(500, e.Message.ToString());
        }
    }
     [HttpGet("/api/Xsjbxx_news/AuditAllData")]
    public IActionResult AuditAllData(String GH,String XM,String status,String XXID, String CJPC)
    {
        
        _db.Database.ExecuteSqlCommand($"update PG_B_XSJBXX_New set 审核卡号={GH},审核姓名={XM},审核状态={status},审核时间= GETDATE() where XXID={XXID} and CJPC={CJPC}");
         return NoContent();
    }
    [HttpGet("/api/Xsjbxx_news/RemoveAllData")]
   public IActionResult RemoveAllData(String GH,String XM,String XXID, String CJPC){
         _db.Database.ExecuteSqlCommand($"update PG_B_XSJBXX_New set 删除卡号={GH},删除姓名={XM},是否删除=1,删除时间= GETDATE() where XXID={XXID}  and  CJPC={CJPC}");
         return NoContent();
    }
    [HttpGet("/api/Xsjbxx_news/GetData")]
    public IActionResult GetData(String XXID, String CJPC,String query,string order,int limit,int skip,String viewMode)
    {
        //
        Console.WriteLine("query "+query);
        //
        
         var datas = _db.PG_B_XSJBXX_New.Where("XXID == @0 and CJPC == @1 and (是否删除 ==0 or 是否删除 == null)",XXID,CJPC);
         if(viewMode == "是")
         datas = datas.Where("审核状态 ==\"通过\"");
         if(query != null)
         datas = datas.Where(query);
         var sums = new String[29];
        sums[0]="合计";
        sums[4]= "通过:"+datas.Where(e=>e.审核状态=="通过").Count();
        sums[4] += ",待审核:"+datas.Where(e=>e.审核状态=="待审核").Count();
        sums[5]= "学生数:"+datas.Select(e=>e.XSXH).Distinct().Count();
        sums[7]= "女:"+datas.Where(e=>e.XZ_XB=="女").Count();
        sums[8]= "少数民族:"+(datas.Select(e=>e.XZ_MZ).Count()-datas.Where(e=>e.XZ_MZ=="汉族").Count());
        sums[9]= "辍学数:"+datas.Where(e=>e.XZ_XJZT=="辍学").Count();
        sums[12]= "军队:"+(datas.Select(e=>e.XZ_SFJD).Count()-datas.Where(e=>e.XZ_SFJD=="否").Count());
        sums[15]= "农村:"+datas.Where(e=>e.XZ_SFNCHK=="是").Count();
        sums[16]= "订单:"+datas.Where(e=>e.XZ_SFDDPY=="是").Count();
        sums[17]= "贫困:"+datas.Where(e=>e.XZ_SFPKH=="是").Count();
        sums[23]= "系部数:"+datas.Select(e=>e.BMMC).Distinct().Count();
        sums[25]= "班级数:"+datas.Select(e=>e.BJMC).Distinct().Count();
        sums[26]= "专业数:"+datas.Select(e=>e.ZYMC).Distinct().Count();
        sums[28]= "方向数:"+datas.Select(e=>e.ZYFXMC).Distinct().Count();
        
        dynamic temp = new  ExpandoObject();
        temp.sums = sums;
        temp.total = datas.Count();
        temp.values = datas.OrderBy(order).Skip(skip).Take(limit).ToArray();
        
        return this.Ok(temp);
    }
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] PG_B_XSJBXX_New model)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values
                                .SelectMany(v => v.Errors)
                                .Select(e => e.Exception.Message));
                return StatusCode(500, message);
            }
            _db.PG_B_XSJBXX_New.Add(model);
            await _db.SaveChangesAsync();

            return Created(model);
        }
        catch (Exception e)
        {
            _log.LogError(this.User.Identity.Name + "," + e.ToString());
            return StatusCode(500, e.Message.ToString());
        }
    }
    [EnableQuery]
    public IActionResult Get()
    {
        try
        {
            return Ok(_db.PG_B_XSJBXX_New);
        }
        catch (Exception e)
        {
            _log.LogError(this.User.Identity.Name + "," + e.ToString());
            return StatusCode(500, e.Message.ToString());
        }
    }
    [HttpPost]
    public IActionResult BulkAddXsjbxx_new(ODataActionParameters parameters)
    {
        
        var Xsjbxx_new = (IEnumerable<PG_B_XSJBXX_New>)parameters["Xsjbxx_new"];
        //
      
         _db.BulkInsert<PG_B_XSJBXX_New>( new List<PG_B_XSJBXX_New>(Xsjbxx_new));
        // Your data access layer logic goes here.
        return this.Ok(HttpStatusCode.NoContent);
    }
}